package com.detooa.detooa.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.boot.SpringApplication;

import com.alibaba.fastjson.JSONObject;
import com.detooa.common.exception.UtilException;
import com.detooa.detooa.config.DataEaseConfig;
import com.detooa.detooa.utils.bean.de.request.DeTreeParamsVo;
import com.detooa.detooa.utils.bean.de.response.BaseDeVo;
import com.detooa.detooa.utils.bean.de.response.DeLinkVo;
import com.detooa.detooa.utils.bean.de.response.DeTreeVo;

import lombok.extern.log4j.Log4j2;
import okhttp3.Response;

/**
 * DataEase 工具栏
 */
@Log4j2
public class DeUtils {

    public static String aesEncrypt(String src, String secretKey, String iv) throws Exception {
        byte[] raw = secretKey.getBytes("UTF-8");
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv1 = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv1);
        byte[] encrypted = cipher.doFinal(src.getBytes("UTF-8"));
        return Base64.encodeBase64String(encrypted);

    }

    /**
     * 获取树
     * 
     * @return
     * @throws Exception
     */
    public static String tree() throws Exception {

        DeTreeParamsVo paramsVo = new DeTreeParamsVo();
        paramsVo.setPanelType("self");
        paramsVo.setSort("create_time desc,node_type desc,name asc");

        String body = JSONObject.toJSONString(paramsVo);

        Response response = OkHttpUtils.post(DataEaseConfig.deBaseUrl + "/panel/group/tree", "application/json;charset=UTF-8", body, headers());
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            log.info(responseBody);
            return responseBody;
        }
        return null;
    }

    public static DeTreeVo toDeTreeVo(String jsonStr) {
        DeTreeVo deTreeVo = JSONObject.parseObject(jsonStr, DeTreeVo.class);
        return deTreeVo;
    }

    public static Map<String, String> headers() {
        Map<String, String> headers = new HashMap<String, String>();
        try {
            String signature = aesEncrypt(DataEaseConfig.deAccessKey + "|" + UUID.randomUUID().toString() + "|" + System.currentTimeMillis(),
                    DataEaseConfig.deSecretKey, DataEaseConfig.deAccessKey);
            headers.put("Accept", "application/json;charset=UTF-8");
            headers.put("accessKey", DataEaseConfig.deAccessKey);
            headers.put("signature", signature);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return headers;
    }

    /**
     * 当前链接信息
     * 
     * @param resourceId
     * @return
     * @throws IOException
     */
    public static DeLinkVo currentGenerate(String resourceId) throws IOException {
        Response response = OkHttpUtils.post(DataEaseConfig.deBaseUrl + "/api/link/currentGenerate/" + resourceId, "application/json;charset=UTF-8",
                "{}", headers());
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            log.info(responseBody);
            JSONObject result = JSONObject.parseObject(responseBody);
            if (result.getBoolean("success")) {
                return JSONObject.parseObject(result.getString("data"), DeLinkVo.class);
            } else {
                throw new UtilException(result.getString("message"));// 异常信息
            }
        }
        return null;
    }

    /**
     * 短连接-压缩链接
     * 
     * @param resourceId
     * @return
     * @throws IOException
     */
    public static BaseDeVo shortUrl(String resourceId) throws IOException {
        Map<String, String> body = new HashMap<String, String>();
        body.put("resourceId", resourceId);
        Response response = OkHttpUtils.post(DataEaseConfig.deBaseUrl + "/api/link/shortUrl", "application/json;charset=UTF-8",
                JSONObject.toJSONString(body), headers());
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            log.info(responseBody);
            return JSONObject.parseObject(responseBody, BaseDeVo.class);
        }
        return null;
    }

    /**
     * 启用-禁用链接分享
     * 
     * @param resourceId
     * @return
     * @throws IOException
     */
    public static BaseDeVo switchLink(String resourceId, boolean valid) throws IOException {
        Map<String, Object> body = new HashMap<String, Object>();
        body.put("resourceId", resourceId);
        body.put("valid", valid);
        Response response = OkHttpUtils.post(DataEaseConfig.deBaseUrl + "/api/link/switchLink", "application/json;charset=UTF-8",
                JSONObject.toJSONString(body), headers());
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            log.info(responseBody);
            return JSONObject.parseObject(responseBody, BaseDeVo.class);
        }
        return null;
    }

    /**
     * 启用-禁用链接分享
     * 
     * @param resourceId
     * @return
     * @throws IOException
     */
    public static boolean resetOverTime(String resourceId, long overTime) throws IOException {
        Map<String, Object> body = new HashMap<String, Object>();
        body.put("resourceId", resourceId);
        body.put("overTime", overTime);
        Response response = OkHttpUtils.post(DataEaseConfig.deBaseUrl + "/api/link/resetOverTime", "application/json;charset=UTF-8",
                JSONObject.toJSONString(body), headers());
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            log.info(responseBody);
            return JSONObject.parseObject(responseBody, BaseDeVo.class).isSuccess();
        }
        return false;
    }

    /**
     * 启用密码
     * 
     * @param resourceId
     * @return
     * @throws IOException
     */
    public static boolean enablePwd(String resourceId, long enablePwd) throws IOException {
        Map<String, Object> body = new HashMap<String, Object>();
        body.put("resourceId", resourceId);
        body.put("enablePwd", enablePwd);
        Response response = OkHttpUtils.post(DataEaseConfig.deBaseUrl + "/api/link/enablePwd", "application/json;charset=UTF-8",
                JSONObject.toJSONString(body), headers());
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            log.info(responseBody);
            return JSONObject.parseObject(responseBody, BaseDeVo.class).isSuccess();
        }
        return false;
    }

    /**
     * 启用密码
     * 
     * @param resourceId
     * @return
     * @throws IOException
     */
    public static boolean resetPwd(String resourceId, String password) throws IOException {
        Map<String, Object> body = new HashMap<String, Object>();
        body.put("resourceId", resourceId);
        body.put("password", password);
        Response response = OkHttpUtils.post(DataEaseConfig.deBaseUrl + "/api/link/resetPwd", "application/json;charset=UTF-8",
                JSONObject.toJSONString(body), headers());
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            log.info(responseBody);
            return JSONObject.parseObject(responseBody, BaseDeVo.class).isSuccess();
        }
        return false;
    }
    
    public static void main(String[] args) throws Exception
    {
        System.out.println(currentGenerate("07f83252-9bbb-11ee-888a-6fd7345aaded"));
    }

}
